package org.iweb.web.filter;

import java.util.HashMap;
import java.util.Map;

import org.iweb.init.AbstractRegister;
import org.iweb.init.Register;
import org.iweb.init.scanner.AnnotationScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({ "rawtypes", "unchecked" })
@Register(name = "FilterRegister")
public class FilterRegister extends AbstractRegister {

	Logger log = LoggerFactory.getLogger(FilterRegister.class);

	private Map<String, Class> filters;

	public void addFilter(String name, Class clazz) {
		Class c = getFilters().get(name);
		if (c == null) {
			getFilters().put(name, clazz);
			log.debug("Register filter " + clazz.getName() + " with name: "
					+ name);
		}
	}

	public Map<String, Class> getFilters() {
		if (filters == null)
			filters = new HashMap<String, Class>();
		return filters;
	}

	@Override
	public void populate(AnnotationScanner scanner) {
		
		Map<String, Object> annotatedClasses = scanner.getClasses().get(
				Filter.class.getName());

		if (annotatedClasses != null) {
			Filter ann;
			Class c;
			for (Object obj : annotatedClasses.values()) {

				if (obj instanceof Class) {
					c = (Class) obj;
					ann = (Filter) c.getAnnotation(Filter.class);
					addFilter(ann.beanName(), c);
				}
			}
		}
		
	}

	@Override
	public void clear() {
		getFilters().clear();
	}
	
	@Override
	public Long getNumReg() {
		return new Long(getFilters().size());
	}

}
